﻿using SuperSocket.ProtoBase;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Text;

namespace EDC.DNC.MSAD.NB.HttpClient
{
    internal class HttpChunkPipeLineFilter : TerminatorPipelineFilter<HttpRequest>
    {
        static ReadOnlyMemory<byte> _terminator = new byte[] { 0x0d, 0x0a }.AsMemory();

        readonly HttpRequest _request;

        public HttpChunkPipeLineFilter(HttpRequest request)
             : base(_terminator)
        {
            _request = request ?? throw new ArgumentNullException(nameof(request));
        }

        protected override HttpRequest DecodePackage(ref ReadOnlySequence<byte> buffer)
        {
            var chunksizeString = buffer.GetString(Encoding.UTF8);

            if (string.IsNullOrEmpty(chunksizeString))
                throw new ArgumentNullException("chunksizeString");

            var chunkSize = Convert.ToInt32(chunksizeString, 16);//16转换到10进制

            if (chunkSize == 0)
                throw new ArgumentNullException("chunkSize");

            NextFilter = new HttpBodyPipelineFilter(chunkSize, _request);

            return default;
        }
    }
}
